<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      
      <el-form-item label="省" prop="provinceId">
        <el-select v-model="queryParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
           <el-option
                v-for="item in provinceData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="市" prop="cityId">
        <el-select v-model="queryParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
           <el-option
                v-for="item in cityData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区/县" prop="areaId">
        <el-select v-model="queryParams.areaId" placeholder="请选择区/县" clearable>
           <el-option
                v-for="item in areaData"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button plain icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
        >新增</el-button>
      </el-col>-->
      <!--<el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:difference:edit']"
        >修改</el-button>
      </el-col>-->
      <!--<el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:difference:remove']"
        >删除</el-button>
      </el-col>-->
      <!--<el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:difference:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="differenceList" stripe>
      <!--<el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="省" align="center" prop="province" />
      <el-table-column label="市" align="center" prop="city" />
      <el-table-column label="区/县" align="center" prop="area" />
      <el-table-column label="维护人" align="center" prop="maintainer" />
      <el-table-column label="维护人所属单位" align="center" prop="maintainerDepartment" />     
      <el-table-column label="维护日期" align="center" prop="maintainTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.maintainTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.rows"
      @pagination="getList"
    />

    <!-- 添加或修改区县致死性差异性指标权重对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="differenceRef" :model="form" :rules="rules" label-width="120px">
      	<p class="dialogTitle">{{title}}</p>
       <el-row>
  			<el-col :span="12">
	        <el-form-item label="地区" prop="">
	          {{form.province}}-{{form.city}}-{{form.area}}
	        </el-form-item>
	    	</el-col>
	       
       	</el-row>
       			
   			<el-row>
   				<el-col :span="7">
	       		<el-form-item label="维护人" prop="">
	       			{{form.maintainer}}		          
		        </el-form-item>
	       	</el-col>
	       	<el-col :span="10">
	       		<el-form-item label="维护人单位" prop="">
	       			{{form.maintainerDepartment}}		          
		        </el-form-item>
	       	</el-col>
	       	<el-col :span="7">
	       		<el-form-item label="维护人日期" prop="">
	       			{{form.maintainTime}}		          
		        </el-form-item>
	       	</el-col>
   			</el-row>
   			
   			<el-row>
   				<el-table :data="tableList">			      
			      <el-table-column label="指标名称" align="center" prop="indexName" width="100px" />
			      <el-table-column label="指标值" align="center" prop="value" width="80px" />
			      <el-table-column label="权重值" align="center" prop="weightValue" >
			      	<template #default="scope">
			          <el-input v-model="scope.row.weightValue"  />
			        </template>
			      	
			      </el-table-column>
			      <el-table-column label="说明" align="center" prop="explain" />
			      <!--<el-table-column label="附件" align="center" prop="maintainerDepartment" />     
			      <el-table-column label="附件" align="center" prop="maintainTime" width="180">
			        <template #default="scope">
			          <span>{{ parseTime(scope.row.maintainTime, '{y}-{m}-{d}') }}</span>
			        </template>
			      </el-table-column>-->
			      <el-table-column label="附件" align="center" prop="file" class-name="small-padding fixed-width">
			        <template #default="scope">
			          <el-button
			          	v-for="item in scope.row.file"
			            type="text"
			            :key="item.attachId"
			            @click="downFile(item.attachId)"
			          >{{item.attachName}}</el-button>
			        </template>
			      </el-table-column>
			    </el-table>
   			</el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button plain @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { modellistDifference, getModelDifference, delDifference, updateModelDifference } from "@/api/modelmanage/modeldifference";
import { getProvince, getChildArea} from "@/api/system/division";
import { getUserId, setUserId } from '@/utils/auth'
import { isDecimal } from '@/utils/validate'
import useUserStore from '@/store/modules/user'

const userStore = useUserStore();
const { proxy } = getCurrentInstance();

const differenceList = ref([]);
const tableList = ref([]);
const isEdit = ref(false);
const isEditFile = ref(false);
const isShow = ref(true);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const submitTime = ref("");//提交时间
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县

const provinceFormData = ref([]);//表单省 
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县
const taskNameData = ref([]);
const isShowCustom1 = ref(false);
const isShowCustom2 = ref(false);
const isShowCustom3 = ref(false);
const isShowCustom4 = ref(false);
const isShowCustom5 = ref(false);
const clickNum = ref(0);

const data = reactive({
  form: {},
  queryParams: {
    page: 1,
    rows: 10,
    
    provinceId: null,
    cityId: null,
    areaId: null,
    
  },
  rules: {
    taskCode: [
      { required: true, message: "任务编号不能为空", trigger: "blur" }
    ],
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    province: [
      { required: true, message: "省不能为空", trigger: "blur" }
    ],
    provinceId: [
      { required: true, message: "省不能为空", trigger: "change" }
    ],
    city: [
      { required: true, message: "市不能为空", trigger: "blur" }
    ],
    cityId: [
      { required: true, message: "市不能为空", trigger: "blur" }
    ],
    area: [
      { required: true, message: "区/县不能为空", trigger: "blur" }
    ],
    areaId: [
      { required: true, message: "区/县 不能为空", trigger: "blur" }
    ],
    building: [
      { required: true,  trigger: "blur", validator: isDecimal }
    ],
    buildingExplain: [
      { required: true, message: "建筑物说明不能为空", trigger: "blur" }
    ],
    peopleNum: [
      { required: true,  trigger: "blur", validator: isDecimal }
    ],
    peopleNumExplain: [
      { required: true, message: "人口说明不能为空", trigger: "blur" }
    ],
    terrain: [
      { required: true,  trigger: "blur", validator: isDecimal  }
    ],
    terrainExplain: [
      { required: true, message: "地形地貌说明不能为空", trigger: "blur" }
    ],
    traffic: [
      { required: true, trigger: "blur", validator: isDecimal }
    ],
    trafficExplain: [
      { required: true, message: "道路交通说明不能为空", trigger: "blur" }
    ],
    climate: [
      { required: true,  trigger: "blur", validator: isDecimal  }
    ],
    climateExplain: [
      { required: true, message: "气候说明不能为空", trigger: "blur" }
    ],
    createName: [
      { required: true, message: "创建人姓名不能为空", trigger: "blur" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询区县致死性差异性指标权重列表 */
function getList() {
  loading.value = true;
  modellistDifference(queryParams.value).then(response => {
  	if(response.data!=null){
  		differenceList.value = response.data.rows;
    	total.value = response.data.total;
  	}    
    loading.value = false;
  });
}

/** 获取省列表 */
function getProvinceData() {
	getProvince().then(response => {
	    provinceData.value = response.data;
	});
}

function getProvinceFormData() {
	getProvince().then(response => {
	    provinceFormData.value = response.data;
	});

}

function editProvinceFormData(provinceId,cityId) {
	getProvince().then(response => {
	    provinceFormData.value = response.data;
	});
	getChildArea(provinceId).then(response => {
    cityFormData.value = response.data;
	});
	getChildArea(cityId).then(response => {
	    areaFormData.value = response.data;
	});
}

function chooseProvince(value){
	queryParams.value.cityId = null;
	queryParams.value.areaId = null;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value).then(response => {
    cityData.value = response.data;
	});
//	provinceData.value.map(item => {//遍历数据
//		if(item.id == value){
//			if(item.name == "北京市"||item.name == "天津市"||item.name == "上海市"||item.name == "重庆市"){
//		    cityData.value.push(JSON.parse(JSON.stringify(item)));
//			}else{
//				getChildArea(value).then(response => {
//			    cityData.value = response.data;
//				});
//			}
//			return;
//		}   
//})		
}

function chooseFormProvince(value){
	form.value.city = null;
	form.value.area = null;
	cityFormData.value = [];
	areaFormData.value = [];
	getChildArea(value).then(response => {
    cityFormData.value = response.data;
	});	
}

function chooseCity(value){
	queryParams.value.areaId = null;
	areaData.value = [];
	getChildArea(value).then(response => {
	    areaData.value = response.data;
	});
}

function chooseFormCity(value){
	form.value.area = null;
	areaFormData.value = [];
	getChildArea(value).then(response => {
	    areaFormData.value = response.data;
	});
}
function chooseTaskName(value){
	taskNameData.value.map(item => {//遍历数据
		if(item.taskName == value){
			form.value.taskCode = item.taskNum;
			console.log(form.value.taskCode)
			return;
		}   
	})	

}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    taskCode: null,
    taskName: null,
    province: null,
    provinceId: null,
    city: null,
    cityId: null,
    area: null,
    areaId: null,
    building: null,
    buildingExplain: null,
    buildingFile: null,
    peopleNum: null,
    peopleNumExplain: null,
    peopleNumFile: null,
    terrain: null,
    terrainExplain: null,
    terrainFile: null,
    traffic: null,
    trafficExplain: null,
    trafficFile: null,
    climate: null,
    climateExplain: null,
    climateFile: null,
    customIndicatorName1: null,
    customIndicatorValue1: null,
    customIndicatorExplain1: null,
    customIndicatorFile1: null,
    customIndicatorName2: null,
    customIndicatorValue2: null,
    customIndicatorExplain2: null,
    customIndicatorFile2: null,
    customIndicatorName3: null,
    customIndicatorValue3: null,
    customIndicatorExplain3: null,
    customIndicatorFile3: null,
    customIndicatorName4: null,
    customIndicatorValue4: null,
    customIndicatorExplain4: null,
    customIndicatorFile4: null,
    customIndicatorName5: null,
    customIndicatorValue5: null,
    customIndicatorExplain5: null,
    customIndicatorFile5: null,
    isSubmit: null,
    delFlag: null,
    createName: null,
    createId: null,
    createTime: null,
    submitter: null,
    submitterId: null,
    submitTime: null
  };
  proxy.resetForm("differenceRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  queryParams.value.startTime = submitTime.value? submitTime.value[0] : "";
  queryParams.value.endTime = submitTime.value? submitTime.value[1] : "";
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
	submitTime.value = [];
	cityData.value = [];
	areaData.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

//获取当前日期函数
function getNowFormatDate() {
  let date = new Date(),
    seperator1 = '-', //格式分隔符
    year = date.getFullYear(), //获取完整的年份(4位)
    month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
    strDate = date.getDate() // 获取当前日(1-31)
  if (month >= 1 && month <= 9) month = '0' + month // 如果月份是个位数，在前面补0
  if (strDate >= 0 && strDate <= 9) strDate = '0' + strDate // 如果日是个位数，在前面补0
 
  let currentdate = year + seperator1 + month + seperator1 + strDate 
  return currentdate
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isEdit.value = false;
  isEditFile.value = false;
  clickNum.value = 0;
  isShowCustom1.value = false;
  isShowCustom2.value = false;
  isShowCustom3.value = false;
  isShowCustom4.value = false;
  isShowCustom5.value = false;
  form.value.submitter = userStore.name;
  form.value.submitterId = getUserId();
  form.value.createId = getUserId();
  form.value.createName = userStore.name;
  form.value.submitTime = getNowFormatDate();
  getProvinceFormData();  
  open.value = true;
  title.value = "添加区县致死性差异性指标权重指标权重";
}

function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value
  
  clickNum.value = 0;
  getModelDifference(id).then(response => {
  	//editProvinceFormData(response.data.data.provinceId,response.data.data.cityId)
    form.value = response.data.entity;
    if(form.value.maintainer==null){
    	form.value.maintainer = userStore.name;
    }
    if(form.value.maintainerDepartment==null){
    	form.value.maintainerDepartment = localStorage.getItem("orgName");
    	form.value.maintainerId = getUserId();
    }
    
    if(form.value.maintainTime==null){
    	form.value.maintainTime = getNowFormatDate();
    }else{
    	form.value.maintainTime = parseTime(form.value.maintainTime, '{y}-{m}-{d}')
    }
    tableList.value = response.data.table;
    
    
		open.value = true;
    title.value = "修改区县致死性差异性指标权重";
  });
}

/** 查看按钮操作 */
function handleView(row) {
  reset();
  const id = row.id || ids.value
  isShow.value = false;
  isEdit.value = true;
  isEditFile.value = true;
  isShowCustom1.value = false;
  isShowCustom2.value = false;
  isShowCustom3.value = false;
  isShowCustom4.value = false;
  isShowCustom5.value = false;
  clickNum.value = 0;
  getModelDifference(id).then(response => {
  	//editProvinceFormData(response.data.data.provinceId,response.data.data.cityId)
    form.value = response.data.data;
    
    open.value = true;
    title.value = "查看区县致死性差异性指标权重";
  });
}

// 校验表单项目比例
function checkradio() {
	var chackProportion = 0;
  tableList.value.map(item => {//遍历数据
  	console.log(parseFloat(item.weightValue))
  	//chackProportion += parseFloat(item.weightValue) == 100 ? true : false
		chackProportion += parseFloat(item.weightValue)
	})    
   
  if(chackProportion == 100){
  	return true 
  }else{
  	return false
  }
   
}

/** 提交按钮 */
function submitForm() {  
  const dataForm = {
  	id:form.value.id,
  	maintainer: form.value.maintainer,
  	maintainerDepartment: form.value.maintainerDepartment,
  	maintainerId: form.value.maintainerId,
  	dataList:tableList.value
  }
  
  proxy.$refs["differenceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
      	if(checkradio()){
      		updateModelDifference(dataForm).then(response => {
	          proxy.$modal.msgSuccess("修改成功");
	          open.value = false;
	          getList();
	        });
      	}else{
      		proxy.$modal.msgError("各指标权重值之和需等于100");
      	}
        
      } else {
        addDifference(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}


function downFile(attachId){
	location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId="+ encodeURIComponent(attachId);
}

getList();
getProvinceData();
</script>
